package com.gla.market.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gla.market.R;
import com.gla.market.adapter.FYH_VedioAdapter;
import com.gla.market.constant.Constants;
import com.gla.market.entity.Commodity;
import com.gla.market.entity.FYH_Vedio;
import com.gla.market.utils.NetUtil;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.IOException;
import java.util.List;

import cn.jzvd.JZVideoPlayerStandard;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class Video_FYHActivity extends AppCompatActivity{
    private String vdoid;
    private static final String lost = "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4";

    private FYH_Vedio thisvdo;

    private Commodity tocom;

    private TextView cmname, vshopname, vprice, cmback;
    private ImageView vshopphoto;
    private LinearLayout cmcard;

    //定义一个自己的context
    private Context mContext;

    private ProgressBar commodityProgressBar;

    //下拉刷新的layout
    private SwipeRefreshLayout mRefreshLayout;
    private GridView recommendProductGridView;

    private List<FYH_Vedio> vl;
    private FYH_VedioAdapter va;

    //商店信息
    private Handler uiHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case -1:
                    //网络请求失败
                    Toast.makeText(mContext, "网络请求失败！", Toast.LENGTH_SHORT).show();
                    break;
                case 0:
                    //网络请求成功，但是返回状态为失败
                    Toast.makeText(mContext, msg.obj == null ? "获取商店数据失败！" : msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    initVideoView();
                    GetCommodityMessage();
                    GetVdobytp();
                    break;
                case 3:
                    vprice.setText("￥" + tocom.getPriceShow());
                    vshopname.setText(tocom.getName());
                    if(!"".equals(tocom.getPhoto())) {
                        ImageLoader.getInstance().displayImage(tocom.getPhoto(), vshopphoto);
                    }else{
                        vshopphoto.setImageResource(R.drawable.fyh_goods_mr);
                    }
                    cmcard.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(Video_FYHActivity.this, Commodity_FYHActivity.class);
                            //将对应的产品id传到详情界面
                            intent.putExtra("id", tocom.getId().toString());
                            startActivity(intent);
                        }
                    });
                    break;
                case 4:
                    va = new FYH_VedioAdapter(mContext, vl);
                    recommendProductGridView.setAdapter(va);
                    //设置gridView点击事件
                    recommendProductGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            TextView tvid = view.findViewById(R.id.vid);
                            Intent intent = new Intent(Video_FYHActivity.this, Video_FYHActivity.class);
                            intent.putExtra("id", tvid.getText().toString());
                            startActivity(intent);
                        }
                    });
                    commodityProgressBar.setVisibility(View.GONE);
                    recommendProductGridView.setVisibility(View.VISIBLE);
                    break;
                default:
                    break;
            }
            //判断刷新动画
            if (mRefreshLayout.isRefreshing()) {
                //停止动画
                mRefreshLayout.setRefreshing(false);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_fyhactivity);
        Intent intent = getIntent();
        vdoid = intent.getStringExtra("id");

        mContext = this;

        mRefreshLayout = findViewById(R.id.refresh_layout);
        commodityProgressBar = findViewById(R.id.vbar);
        recommendProductGridView = findViewById(R.id.evaluationlist);
        cmname = findViewById(R.id.commodity_name);
        vshopname = findViewById(R.id.v_shop_name);
        vprice = findViewById(R.id.v_price);
        vshopphoto = findViewById(R.id.v_shop_photo);
        cmback = findViewById(R.id.commodity_back);
        cmcard = findViewById(R.id.cmcard);

        cmname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(mContext, thisvdo.getName(), Toast.LENGTH_SHORT).show();
            }
        });

        cmback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mRefreshLayout.setOnRefreshListener(mRefreshListener);
        GetVedio();
    }

    private void initVideoView() {
        String url = thisvdo.getUrl();
        if("".equals(url)) url = lost;
        JZVideoPlayerStandard jzVideoPlayerStandard =  findViewById(R.id.vv_video);
        String name = thisvdo.getName();
        jzVideoPlayerStandard.setUp(url, JZVideoPlayerStandard.SCREEN_WINDOW_FULLSCREEN, name);
        if(name.length() > 10) name = name.substring(0, 10) + "...";
        cmname.setText(name);
        jzVideoPlayerStandard.SAVE_PROGRESS=false;//不保存进度
        jzVideoPlayerStandard.startVideo();//自动播放
    }

    //刷新
    private SwipeRefreshLayout.OnRefreshListener mRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            GetVdobytp();
        }
    };

    //获取同类视频
    private void GetVdobytp() {
        String url = Constants.BASE_URL + Constants.GET_FYH_SHOP_URL + Constants.GET_FYH_VEDIOBYTYPE_URL + Constants.typeid(thisvdo.getType_id(), thisvdo.getId());
        NetUtil.doGet(url, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("调试", "错误信息：" + e.toString());
                        Message message = Message.obtain();
                        message.what = -1;
                        uiHandler.sendMessage(message);
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string().trim();
                        com.alibaba.fastjson.JSONObject object = JSON.parseObject(result);
                        Message message = Message.obtain();
                        if (!object.getString("message").contains("JWT") && object.getString("error")==null && object.getInteger("code")==100) {
                            JSONArray array = object.getJSONArray("data");
                            vl = JSONArray.parseArray(array.toString(), FYH_Vedio.class);
                            message.what = 4;
                        } else {
                            message.what = 0;
                        }
                        uiHandler.sendMessage(message);
                    }
                }
        );
    }

    //获取商品
    private void GetCommodityMessage() {
        String url = Constants.BASE_URL + Constants.GET_FYH_SHOP_URL + Constants.GET_FYH_CMBYID_URL + thisvdo.getCommodity_id();
        NetUtil.doGet(url, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("调试", "错误信息：" + e.toString());
                        Message message = Message.obtain();
                        message.what = -1;
                        uiHandler.sendMessage(message);
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string().trim();
                        com.alibaba.fastjson.JSONObject object = JSON.parseObject(result);
                        Message message = Message.obtain();
                        if (!object.getString("message").contains("JWT") && object.getString("error")==null && object.getInteger("code")==100) {
                            JSONObject jshop = object.getJSONObject("data");
                            //获得商品list
                            tocom = JSONObject.parseObject(String.valueOf(jshop), Commodity.class);
                            message.what = 3;
                        } else {
                            message.what = 0;
                        }
                        uiHandler.sendMessage(message);
                    }
                }
        );
    }

    //获取视频
    private void GetVedio() {
        String url = Constants.BASE_URL + Constants.GET_FYH_SHOP_URL + Constants.GET_FYH_ONEVEDIO_URL + vdoid;
        NetUtil.doGet(url, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("调试", "错误信息：" + e.toString());
                        Message message = Message.obtain();
                        message.what = -1;
                        uiHandler.sendMessage(message);
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string().trim();
                        com.alibaba.fastjson.JSONObject object = JSON.parseObject(result);
                        Message message = Message.obtain();
                        if (!object.getString("message").contains("JWT") && object.getString("error")==null && object.getInteger("code")==100) {
                            JSONObject jshop = object.getJSONObject("data");
                            //获得商品list
                            thisvdo = JSONObject.parseObject(String.valueOf(jshop), FYH_Vedio.class);
                            message.what = 2;
                        } else {
                            message.what = 0;
                        }
                        uiHandler.sendMessage(message);
                    }
                }
        );
    }
}